import { defineStore } from 'pinia';
import { ref } from 'vue';

export const useThemeStore = defineStore('theme', () => {
  // 主题模式: light or dark
  const theme = ref<'light' | 'dark'>('light');

  // 是否已初始化
  const isInitialized = ref(false);

  // 设置主题
  const setTheme = (mode: 'light' | 'dark') => {
    theme.value = mode;
    document.documentElement.setAttribute('data-theme', mode);
    localStorage.setItem('theme', mode);
  };

  // 切换主题
  const toggleTheme = () => {
    const newTheme = theme.value === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
  };

  // 初始化主题
  const initTheme = () => {
    if (isInitialized.value) {
      return;
    }

    // 从 cookie 中获取主题设置
    const savedTheme = localStorage.getItem('theme') as 'light' | 'dark' | undefined;
    if (savedTheme) {
      setTheme(savedTheme);
    } else {
      // 如果没有保存的主题，则根据系统主题设置
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      setTheme(prefersDark ? 'dark' : 'light');
    }

    isInitialized.value = true;
  };

  return {
    theme,
    setTheme,
    toggleTheme,
    initTheme
  };
});
